package com.example.demo.concurrent.ReentrantReadWriteLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 结论 : 读读可以并发,读写,写写是互斥的.
 */
@Slf4j(topic = "c.DataContainer")
class DataContainer{
    private int data;
    private static ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock rl = rw.readLock();//读锁
    private static ReentrantReadWriteLock.WriteLock wl = rw.writeLock();//写锁

    public int read() {
        log.debug("获取读锁");
        rl.lock();
        try{
            log.debug("读取...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return data;
        }finally {
            rl.unlock();
            log.debug("释放读锁");
        }
    }

    public void write() {
        log.debug("获取写锁");
        wl.lock();
        try{
            log.debug("写入...");
        }finally {
            log.debug("释放写锁");
            wl.unlock();
        }
    }
}
@Slf4j(topic = "c.TestDemo1")
public class TestDemo1 {

    public static void main(String[] args) throws InterruptedException {
        DataContainer dataContainer = new DataContainer();
        new Thread(()->{
            dataContainer.read();
        },"t1").start();
        new Thread(()->{
            dataContainer.write();
        },"t2").start();
    }
}